﻿using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using Opalis.QuickIntegrationKit;

namespace LocalComputerSecurity
{
    [OpalisObject("Add Local User")]
    public class AddLocalUser : IOpalisObject
    {
        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Computer Name");
            designer.AddInput("User Name");
            designer.AddInput("User Password").PasswordProtect();
            designer.AddInput("User Full Name").NotRequired();
            designer.AddOutput("User Name");
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            String userName = String.Empty;
            String password = String.Empty;
            String userFullName = String.Empty;
            String computerName = String.Empty;
            userName = request.Inputs["User Name"].AsString();
            password = request.Inputs["User Password"].AsString();
            userFullName = request.Inputs["User Full Name"].AsString();
            computerName = request.Inputs["Computer Name"].AsString();

            DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://" + computerName); 
            DirectoryEntries entries = hostMachineDirectory.Children;
            bool userExists = false; 
            foreach (DirectoryEntry each in entries)
            { 
                userExists = each.Name.Equals(userName,StringComparison.CurrentCultureIgnoreCase); 
                if (userExists) 
                    break; 
            } 
     
            if (false == userExists) 
            {
                DirectoryEntry obUser = entries.Add(userName, "User"); 
        
                if(userFullName == String.Empty) { obUser.Properties["FullName"].Add(userFullName); }
                else { obUser.Properties["FullName"].Add("Local user"); }
                
                obUser.Invoke("SetPassword", password); 
                obUser.Invoke("Put", new object[] {"UserFlags", 0x10000}); 
                obUser.CommitChanges(); 
            }
            response.Publish("User Name", userName);
        }
    }
}
